#include "iothread.h"
#include "message.h"

namespace ProcessRouter {

IOThread::IOThread()
    : m_task(this, &IOThread::taskLoop)
    , m_evrunMode()
{
    m_loop = EV_DEFAULT;
    ev_set_userdata(m_loop, (void *)&m_listeners);
    m_task.reg();
}

IOThread::~IOThread()
{
}

void IOThread::addListener(Listener *listener)
{
    std::list<Listener*>::iterator it;
    for (it = m_listeners.begin(); it != m_listeners.end(); it ++)
        if (listener->fd() == (*it)->fd())
            return;

    m_listeners.push_back(listener);

    ev_io_start (m_loop, listener->watcher());
}

void IOThread::removeListener(Listener *listener)
{
    std::list<Listener*>::iterator it;
    for (it = m_listeners.begin(); it != m_listeners.end(); it ++) {
        if (listener->fd() == (*it)->fd()) {
            ev_io_stop(m_loop, (*it)->watcher());
            m_listeners.erase(it);
            return;
        }
    }
}

void IOThread::forkLoop()
{
    m_task.unreg();

    ev_loop_fork(m_loop);
    
    //ev_break(m_loop, EVBREAK_ALL);
    ev_loop_destroy(m_loop);

    m_loop = EV_DEFAULT;
    m_listeners.clear();
    ev_set_userdata(m_loop, (void *)&m_listeners);
}

void IOThread::threadMain()
{
    ev_run(m_loop, 0);
}

void IOThread::taskLoop(Rooftop::Task<IOThread> *)
{
    ev_run(m_loop, EVRUN_NOWAIT);
}

}
